package online.sixfish.doubao.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import online.sixfish.common.api.ApiResult;
import online.sixfish.common.dto.PageDTO;
import online.sixfish.common.pojo.User;
import online.sixfish.common.utils.SecurityUtil;
import online.sixfish.doubao.model.dto.LoginDTO;
import online.sixfish.doubao.model.dto.RegisterDTO;
import online.sixfish.doubao.model.entity.BmsPost;
import online.sixfish.doubao.model.vo.ProfileVO;
import online.sixfish.doubao.service.ArticleService;
import online.sixfish.doubao.service.IBmsPostService;
import online.sixfish.doubao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/ums/user")
public class UmsUserController extends BaseController {
    @Resource
    private UserService userService;


    @Resource
    private ArticleService articleService;

    @PostMapping("/updateAvatar")
    @PreAuthorize("hasAnyRole('user','admin')")
    public ApiResult updateAvatar(@RequestParam String fileName) {
        userService.updateAvatar(fileName);
        return ApiResult.success();
    }

    @PostMapping("/update")
    @PreAuthorize("hasAnyRole('user','admin')")
    public ApiResult update(@RequestBody User user) {
        user.setId(SecurityUtil.currentUserId());
        userService.updateById(user);
        return ApiResult.success();
    }

    @GetMapping("/id/{id}")
    @PreAuthorize("hasAnyRole('user','admin')")
    public ApiResult findById(@PathVariable String id) {
        User user = userService.findById(id);
        if (Objects.nonNull(user)) {
            user.setPassword(null);
        }
        return ApiResult.success(user);
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyRole('user','admin')")
    public ApiResult getInfoById(@PathVariable String id) {
        ProfileVO profile = userService.getUserProfile(id);
        return ApiResult.success(profile);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ApiResult<Map<String, Object>> register(@Valid @RequestBody RegisterDTO dto) {
        User user = userService.executeRegister(dto);
        if (ObjectUtils.isEmpty(user)) {
            return ApiResult.failed("账号注册失败");
        }
        Map<String, Object> map = new HashMap<>(16);
        map.put("user", user);
        return ApiResult.success(map);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResult<Map<String, String>> login(@Valid @RequestBody LoginDTO dto) {
        String token = userService.executeLogin(dto);
        if (ObjectUtils.isEmpty(token)) {
            return ApiResult.failed("账号密码错误");
        }
        Map<String, String> map = new HashMap<>(16);
        map.put("token", token);
        log.info("登录成功");
        return ApiResult.success(map, "登录成功");
    }

    @PreAuthorize("hasAnyRole('user','admin')")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public ApiResult<User> getUser(@RequestParam String username) {
        User user = userService.getUserByUsername(username);
        return ApiResult.success(user);
    }


    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ApiResult<Object> logOut() {
        return ApiResult.success(null, "注销成功");
    }

    @GetMapping("/{username}")
    @PreAuthorize("hasAnyRole('user','admin')")
    public ApiResult<Map<String, Object>> getUserByName(@PathVariable("username") String username,
                                                        @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map<String, Object> map = new HashMap<>(16);
        User user = userService.getUserByUsername(username);
        Assert.notNull(user, "用户不存在");
//        Page<BmsPost> page = iBmsPostService.page(new Page<>(pageNo, size),
//                new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getUserId, user.getId()));
        PageDTO pageDTO = articleService.getArticleByUserId(user.getId(), pageNo, size);

        map.put("user", user);
        map.put("topics", pageDTO);
        return ApiResult.success(map);
    }

//    @PostMapping("/update")
//    @PreAuthorize("hasAnyRole('user','admin')")
//    public ApiResult<User> updateUser(@RequestBody User user) {
//        userService.updateById(user);
//        return ApiResult.success(user);
//    }
}
